<?php
// +----------------------------------------------------------------------
// | NewThink [ Think More,Think Better! ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2018 http://www.newthink.cc All rights reserved.
// +----------------------------------------------------------------------
// | 版权所有：山西创泰网络科技有限公司
// +----------------------------------------------------------------------
// | Author: ayy  Date:2019/7/24 Time:15:36
// +----------------------------------------------------------------------

namespace app\common\service;


use think\Db;

class InletFlueGasService extends BaseService
{
    /**
     * 实时企业 - 单公司 - 单设施 - 脱硫脱硝 入口烟气量天/小时/分钟有效值平均值
     * @param int $facility_id 设施ID
     * @param string $type SO2 NO2
     * @param string $plan_number
     * @param string $day_type day minute hour
     * @return string
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/07/24
     */
    public function getCompanyFacilityInletFlueGasVolumeDay($facility_id, $plan_number, $type = 'SO2', $day_type = 'day')
    {
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';

        if ($type == 'SO2') {
            $table = 'company_industry_monitor_sulfur_minute';
        } else {
            $table = 'company_industry_monitor_nitre_minute';
        }

        $match = [
            'publish_time' => ['$gte' => $startTime, '$lt' => $endTime],
            'facility_id'  => (int)$facility_id
        ];
        $sqlEmission = [
            'aggregate' => $table,
            'pipeline'  => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id'                   => null,
                        'inlet_flue_gas_volume' => ['$sum' => '$inlet_flue_gas_volume'],
                        'count'                 => ['$sum' => 1]
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj = $this->mongodb->executeCommand('huanxin', $commandEmission);
        if ($result = mongoObjToArray($sulfurDataObj)) {
            $result = $result[0]['inlet_flue_gas_volume']/$result[0]['count'];//分钟均值
        } else {
            $result = 0;
        }
        $data = 0;
        if ($day_type == 'day') {
            $data = sprintf('%.5f', $result * 24 * 60);
        } elseif ($day_type == 'hour') {
            $data = sprintf('%.5f', $result * 60);
        } elseif ($day_type == 'minute') {
            $data = sprintf('%.5f', $result);
        }
        return $data;
    }

    /**
     * 实时企业 - 单设施 - 脱硫脱硝  入口污染物浓度计算
     * @param $facility_id
     * @param $plan_number
     * @param string $type
     * @return int|string
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getCompanyFacilityInletConcentration($facility_id, $plan_number, $type = 'SO2')
    {
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';

        if ($type == 'SO2') {
            $table    = 'company_industry_monitor_sulfur_minute';
            $volume_s = '$inlet_sulphur_concentration';
        } else {
            $table    = 'company_industry_monitor_nitre_minute';
            $volume_s = '$in_no2';
        }

        $match = [
            'publish_time' => ['$gte' => $startTime, '$lt' => $endTime],
            'facility_id'  => (int)$facility_id
        ];
        $sqlEmission = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => null,
                        'inlet_concentration' => ['$sum' => [
                            '$multiply' => ['$inlet_flue_gas_volume', $volume_s]
                        ]],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj = $this->mongodb->executeCommand('huanxin', $commandEmission);
        if ($inlet_concentration = mongoObjToArray($sulfurDataObj)) {
            $inlet_concentration = $inlet_concentration[0]['inlet_concentration'];
        } else {
            $inlet_concentration = 0;
        }
        $inlet_gas_volume = $this->getCompanyFacilityInletFlueGasVolumeDay($facility_id, $plan_number, $type) * 7;//入口烟气量

        $result = $inlet_gas_volume ? sprintf('%.3f', $inlet_concentration / $inlet_gas_volume) : 0;
        return $result;
    }

    /**
     * 实时企业/模拟企业 - 单公司 - 单排口 - 脱硫脱硝 入口烟气量天平均值
     * @param int $company_id 公司ID
     * @param int $drain_id 排口ID
     * @param string $type SO2 NO2
     * @param string $plan_number
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/07/25
     */
    public function getCompanyDrainInletFlueGasVolumeDay($company_id, $drain_id,$plan_number, $type = 'SO2')
    {
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';

        if ($type == 'SO2') {
            $table = 'company_industry_monitor_sulfur_minute';
        } else {
            $table = 'company_industry_monitor_nitre_minute';
        }
        //实时企业
        $match = [
            'publish_time' => ['$gte' => $startTime, '$lt' => $endTime],
            'drain_id'     => $drain_id,
            'company_id'   => $company_id
        ];
        $sqlEmission = [
            'aggregate' => $table,
            'pipeline'  => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id'                   => null,
                        'inlet_flue_gas_volume' => ['$sum' => '$inlet_flue_gas_volume'],
                        'count'                 => ['$sum' => 1]
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj   = $this->mongodb->executeCommand('huanxin', $commandEmission);
        $data = 0;
        if ($res = mongoObjToArray($sulfurDataObj)) {
            $data = sprintf('%.5f', $res[0]['inlet_flue_gas_volume'] / $res[0]['inlet_flue_gas_volume'] * 60 *24);
        }
        //模拟企业
        if ($type == 'SO2') {
            $sql = <<<SQL
                SELECT
                    gas_volume - convert(emissions_so2/operation_concentration_so2,decimal(15,5)) as inlet_flue_gas_volume
                FROM
                    company_industry_monitor_simulation_hour_avg
                WHERE
                    company_id = $company_id
                LIMIT 1
SQL;
        } else {
            $sql = <<<SQL
                SELECT
                    gas_volume - convert(emissions_nox/operation_concentration_nox,decimal(15,5)) as inlet_flue_gas_volume
                FROM
                    company_industry_monitor_simulation_hour_avg
                WHERE
                    company_id = $company_id
                LIMIT 1
SQL;
        }
        $monitorInletFlueGasVolume = Db::query($sql);
        if ($monitorInletFlueGasVolume) {
            $data = $monitorInletFlueGasVolume[0]['inlet_flue_gas_volume'] * 24;
        }
        return $data;
    }

    /**
     * 实时企业/模拟企业 - 单公司 - 单排口 - 脱硫脱硝 每小时 入口烟气量之和
     * @param int $company_id 公司ID
     * @param int $drain_id 排口ID
     * @param string $type SO2 NO2
     * @param string $plan_number
     * @return string
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/07/25
     */
    public function getCompanyDrainInletFlueGasVolumeHour($company_id, $plan_number, $drain_id, $type = 'SO2')
    {
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';

        if ($type == 'SO2') {
            $table = 'company_industry_monitor_sulfur_minute';
        } else {
            $table = 'company_industry_monitor_nitre_minute';
        }
        //实时企业
        $match = [
            'publish_time' => ['$gte' => $startTime, '$lt' => $endTime],
            'drain_id'     => $drain_id,
            'company_id'   => $company_id
        ];
        $sqlEmission = [
            'aggregate' => $table,
            'pipeline'  => [
                [
                    '$project' => [
                        '_id'                   => 0,
                        'drain_id'              => 1,
                        'drain_name'            => 1,
                        'company_id'            => 1,
                        'company_name'          => 1,
                        'publish_time'          => 1,
                        'inlet_flue_gas_volume' => 1,
                        'day'                   => ['$substr' => ['$publish_time', 0, 13]]
                    ],
                ],
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id'                   => [
                            'day'          => '$day',
                            'company_id'   => '$company_id',
                            'company_name' => '$company_name',
                            'drain_id'     => '$drain_id',
                            'drain_name'   => '$drain_name',
                        ],
                        'inlet_flue_gas_volume' => ['$sum' => '$inlet_flue_gas_volume'],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj = $this->mongodb->executeCommand('huanxin', $commandEmission);

        if ($data = mongoObjToArray($sulfurDataObj)) {
            return $data;
        }
        //模拟企业
        if ($type == 'SO2') {
            $sql = <<<SQL
                SELECT
                    gas_volume - convert(emissions_so2/operation_concentration_so2,decimal(15,5)) as inlet_flue_gas_volume
                FROM
                    company_industry_monitor_simulation_hour_avg
                WHERE
                    company_id = $company_id
                LIMIT 1
SQL;
        } else {
            $sql = <<<SQL
                SELECT
                    gas_volume - convert(emissions_nox/operation_concentration_nox,decimal(15,5)) as inlet_flue_gas_volume
                FROM
                    company_industry_monitor_simulation_hour_avg
                WHERE
                    company_id = $company_id
                LIMIT 1
SQL;
        }
        if ($data = Db::query($sql)) {
            return $data;
        }
    }

    /**
     * 实时企业/模拟企业 - 单企业 - 减排前 - 脱离脱硝 - 出口烟气量  总和
     * @param $company_id
     * @param string $type
     * @param string $plan_number
     * @return mixed
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/07/29
     */
    public function getCompanyExportFlueGasVolume($company_id,$plan_number, $type = 'SO2')
    {
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';

        //实时企业
        if ($type == 'SO2') {
            $table   = 'company_industry_monitor_sulfur_minute';
            $field   = 'export_flue_gas_volume';
            $field_s = '$export_flue_gas_volume';
        } else {
            $table   = 'company_industry_monitor_nitre_minute';
            $field   = 'aig_flue_flow';
            $field_s = '$aig_flue_flow';
        }

        $match = [
            'publish_time' => ['$gte' => $startTime, '$lt' => $endTime],
            'company_id'   => $company_id
        ];
        $sqlEmission = [
            'aggregate' => $table,
            'pipeline'  => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id'  => null,
                        $field => ['$sum' => $field_s],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj = $this->mongodb->executeCommand('huanxin', $commandEmission);
        $res = mongoObjToArray($sulfurDataObj);
        $data = 0;
        if ($res) {
            $data = $res[0][$field];
        }
        //模拟企业
        if ($type == 'SO2') {
            $sql = <<<SQL
                SELECT
                    sum(convert(emissions_so2/operation_concentration_so2,decimal(15,5))) as gas_volume
                FROM
                    company_industry_monitor_simulation_hour_avg
                WHERE
                    company_id = $company_id
                LIMIT 1
SQL;
        } else {
            $sql = <<<SQL
                SELECT
                    sum(convert(emissions_nox/operation_concentration_nox,decimal(15,5))) as gas_volume
                FROM
                    company_industry_monitor_simulation_hour_avg
                WHERE
                    company_id = $company_id
                LIMIT 1
SQL;
        }
        $gas_volume = Db::query($sql);
        if ($gas_volume) {
            $data = $gas_volume[0]['gas_volume'] * 7 * 24;
        }
        return $data;
    }

    /**
     * 实时企业/模拟企业 - 单企业 - 减排前 - 脱离脱硝 - 出口烟气量  各企业总和
     * @param string $plan_number
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/07/26
     */
    public function getCompanyExportFlueGasVolumeAll($plan_number)
    {
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';

        $true_ids = Db::name('basic_company')->where(['realtime_company' => 1, 'delete_time' => 0])->column('id');

        //实时企业
        $match = [
            'publish_time' => ['$gte' => $startTime, '$lt' => $endTime],
            'company_id'   => ['$in'  => $true_ids]
        ];
        $sqlEmissionSO2 = [
            'aggregate' => 'company_industry_monitor_sulfur_minute',
            'pipeline'  => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id'            => ['company_id' => '$company_id', 'company_name' => '$company_name'],
                        'so2_gas_volume' => ['$sum' => '$export_flue_gas_volume']
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmissionSO2 = new \MongoDB\Driver\Command($sqlEmissionSO2);
        $sulfurDataObjSO2 = $this->mongodb->executeCommand('huanxin', $commandEmissionSO2);
        $resSO2 = mongoObjToArray($sulfurDataObjSO2);

        $sqlEmissionNO2 = [
            'aggregate' => 'company_industry_monitor_nitre_minute',
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id'            => ['company_id' => '$company_id', 'company_name' => '$company_name'],
                        'no2_gas_volume' => ['$sum' => '$aig_flue_flow']
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmissionNO2 = new \MongoDB\Driver\Command($sqlEmissionNO2);
        $sulfurDataObjNO2 = $this->mongodb->executeCommand('huanxin', $commandEmissionNO2);
        $resNO2 = mongoObjToArray($sulfurDataObjNO2);

        $data = [];
        foreach ($resSO2 as $val) {
            foreach ($resNO2 as $value) {
                $item = [];
                $item['company_id']         = $val['_id']->company_id;
                $item['company_name']       = $val['_id']->company_name;
                $item['so2_gas_volume']     = $val['so2_gas_volume'];
                if ($val['_id']->company_id == $value['_id']->company_id) {
                    $item['no2_gas_volume'] = $value['no2_gas_volume'];
                }
                array_push($data, $item);
            }
        }

        $monitor_ids = Db::name('basic_company')->where(['realtime_company' => 0,'delete_time'=>0])->column('id');
        $ids         = implode(',', $monitor_ids);

        //模拟企业
        $sql = <<<SQL
            SELECT
                company_id,company_name,
                sum(convert(emissions_so2/operation_concentration_so2,decimal(15,5)))*7 as so2_gas_volume,
                sum(convert(emissions_nox/operation_concentration_nox,decimal(15,5)))*7 as no2_gas_volume
            FROM
                company_industry_monitor_simulation_hour_avg
            WHERE
                company_id IN ($ids)
            GROUP BY 
                company_id
SQL;
        $gas_volume = Db::query($sql);
        $data       = array_merge($data, $gas_volume);
        return $data;
    }

    /**
     * 实时企业 + 模拟企业 - 单行业  减排前  脱离脱硝 出口烟气量  总和
     * @param $industry_id
     * @param string $type
     * @param string $plan_number
     * @return mixed
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/07/26
     */
    public function getIndustryExportFlueGasVolume($industry_id,$plan_number, $type = 'SO2')
    {
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';

        $companys = Db::name('basic_company')
            ->where(['industry_id' => $industry_id,'delete_time' => 0])
            ->column('id');

        //实时企业
        if ($type == 'SO2') {
            $table   = 'company_industry_monitor_sulfur_minute';
            $field   = 'export_flue_gas_volume';
            $field_s = '$export_flue_gas_volume';
        } else {
            $table   = 'company_industry_monitor_nitre_minute';
            $field   = 'aig_flue_flow';
            $field_s = '$aig_flue_flow';
        }

        $match = [
            'publish_time' => ['$gte' => $startTime, '$lt' => $endTime],
            'company_id'   => ['$in'  => $companys]
        ];
        $sqlEmission = [
            'aggregate' => $table,
            'pipeline'  => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id'  => null,
                        $field => ['$sum' => $field_s],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj = $this->mongodb->executeCommand('huanxin', $commandEmission);
        $data = 0;
        if($res = mongoObjToArray($sulfurDataObj)){
            $data = $res[0][$field];
        }

        //模拟企业
        if ($type == 'SO2') {
            $sql = <<<SQL
                SELECT 
                    sum(convert(emissions_so2/operation_concentration_so2,decimal(15,5))) as gas_volume
                FROM 
                    company_industry_monitor_simulation_hour_avg
                WHERE
                    industry_id = $industry_id
SQL;
        } else {
            $sql = <<<SQL
                SELECT 
                    sum(convert(emissions_nox/operation_concentration_nox,decimal(15,5))) as gas_volume
                FROM 
                    company_industry_monitor_simulation_hour_avg
                WHERE
                    industry_id = $industry_id
SQL;
        }

        $gas_volume = Db::query($sql);
        if ($gas_volume) {
            $data += $gas_volume[0]['gas_volume'] * 7;
        }
        return $data;
    }

    /**
     * 实时企业 + 模拟企业 - 单行业  减排前  脱离脱硝 出口烟气量  各行业总和
     * @param string $plan_number
     * @param string $type
     * @return mixed
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/07/26
     */
    public function getIndustryExportFlueGasVolumeAll($plan_number,$type = 'SO2')
    {
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';

        $industry_ids = Db::name('basic_industry')->column('id');

        //实时企业
        if ($type == 'SO2') {
            $table   = 'company_industry_monitor_sulfur_minute';
            $field   = 'export_flue_gas_volume';
            $field_s = '$export_flue_gas_volume';
        } else {
            $table   = 'company_industry_monitor_nitre_minute';
            $field   = 'aig_flue_flow';
            $field_s = '$aig_flue_flow';
        }

        $match = [
            'publish_time' => ['$gte' => $startTime, '$lt' => $endTime],
            'industry_id'  => ['$in' => $industry_ids]
        ];
        $sqlEmission = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => ['industry_id' => '$industry_id', 'industry_name' => '$industry_name'],
                        $field => ['$sum' => $field_s],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj = $this->mongodb->executeCommand('huanxin', $commandEmission);
        $res = mongoObjToArray($sulfurDataObj);
        $data = [];
        foreach ($res as $val) {
            $item = [];
            $item['industry_id'] = $val['_id']->industry_id;
            $item['$industry_name'] = $val['_id']->industry_name;
            $item['gas_volume'] = $val[$field];
            $data[] = $item;
        }
        $ids = [];
        foreach ($data as $val) {
            $ids[] = $val['industry_id'];
        }
        //模拟企业
        if ($type == 'SO2') {
            $sql = <<<SQL
                SELECT 
                    industry_id,industry_name,sum(convert(emissions_so2/operation_concentration_so2,decimal(15,5)))*7 as gas_volume
                FROM 
                    company_industry_monitor_simulation_hour_avg
                GROUP BY
                    industry_id
SQL;
        } else {
            $sql = <<<SQL
                SELECT 
                    industry_id,industry_name,sum(convert(emissions_nox/operation_concentration_nox,decimal(15,5)))*7 as gas_volume
                FROM 
                    company_industry_monitor_simulation_hour_avg
                GROUP BY
                    industry_id
SQL;
        }

        $gas_volume = Db::query($sql);

        foreach ($gas_volume as $key => &$item) {
            if (in_array($item['industry_id'], $ids)) {
                foreach ($data as &$val) {
                    if ($item['industry_id'] === $val['industry_id']) {
                        $val['gas_volume'] += $item['gas_volume'];
                        unset($gas_volume[$key]);
                    }
                }
            }
        }
        $data = array_merge($data, $gas_volume);
        return $data;
    }


    /**
     * 减排前 - 单设施 - 每天的出口烟气量
     * @param $facilityId
     * @param string $type
     * @param string $plan_number
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/08/02
     */
    public function getCompanyFacilityExportFlueGasVolumeDay($plan_number,$facilityId, $type = 'SO2')
    {
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';

        if ($type == 'SO2') {
            $table   = 'company_industry_monitor_sulfur_minute';
            $field   = 'export_flue_gas_volume';
            $field_s = '$export_flue_gas_volume';
        } else {
            $table   = 'company_industry_monitor_nitre_minute';
            $field   = 'aig_flue_flow';
            $field_s = '$aig_flue_flow';
        }
        $match = [
            'publish_time' => ['$gte' => $startTime, '$lt' => $endTime],
            'facility_id'  => (int)$facilityId,
        ];
        $sqlEmission = [
            'aggregate' => $table,
            'pipeline'  => [
                [
                    '$project' => [
                        '_id'          => 0,
                        'facility_id'  => 1,
                        $field         => 1,
                        'publish_time' => ['$substr' => ['$publish_time', 0, 10]]
                    ],
                ],
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => [
                            'publish_time' => '$publish_time',
                            'facility_id'  => '$facility_id',
                        ],
                        'export_flue_gas_volume' => ['$sum' => $field_s]
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj = $this->mongodb->executeCommand('huanxin', $commandEmission);
        return mongoObjToArray($sulfurDataObj);
    }

    /**
     * 实时企业 - 减排前 - 脱硫脱硝 - 设施运行浓度
     * @param int $facility_id 设施ID
     * @param string $plan_number 预案编号
     * @param string $type SO2  NO2
     * @return string
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/07/25
     */
    public function getCompanyFacilityOperationConcentration($facility_id, $plan_number, $type = 'SO2')
    {
        $emission  = new ControlEmissionService();
        $emissions = $emission->getControlEmissionDayAverageByFacilityId($facility_id, $plan_number);//设施排放量天均值
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number);
        $endTime   = date('Y-m-d',strtotime('-1 day',strtotime($control->getBeforeEndTime($plan_number))));
        $smoke     = (new FlugGasService())->monitorSulfurExitSmokeMinuteAvg($startTime, $endTime, $facility_id, $type);//出口烟气量
        $result    = $smoke ? sprintf('%.3f', $emissions / ($smoke * 24 * 60)) : 0;
        return $result;
    }

    /**
     * 实时企业 - 减排前 - 脱硫脱硝 - 设施运行效率
     * @param string $plan_number 预案编号
     * @param int $facility_id 设施ID
     * @param string $type SO2 NO2
     * @return string
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/07/25
     */
    public function getCompanyFacilityOperatingEfficiency($facility_id, $plan_number, $type = 'SO2')
    {
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';

        if ($type == 'SO2') {
            $table = 'company_industry_monitor_sulfur_minute';
        } else {
            $table = 'company_industry_monitor_nitre_minute';
        }

        //实时企业
        $match = [
            'publish_time'         => ['$gte' => $startTime, '$lt' => $endTime],
            'facility_id'          => (int)$facility_id,
            'operating_efficiency' => ['$nin' => [1, NAN]]
        ];
        $sqlEmission = [
            'aggregate' => $table,
            'pipeline'  => [
                [
                    '$project' => [
                        '_id'                  => 1,
                        'emissions'            => 1,
                        'operating_efficiency' => 1,
                        'facility_id'          => 1,
                        'publish_time'         => 1
                    ],
                ],
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => null,
                        'operating_efficiency' => [
                            '$sum' => [ //求和
                                '$divide' => [ //相除
                                    '$emissions',
                                    ['$subtract' => [1, '$operating_efficiency']] //相减
                                ]
                            ]
                        ],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj   = $this->mongodb->executeCommand('huanxin', $commandEmission);
        $operatingEfficiency = 0;
        if ($res = mongoObjToArray($sulfurDataObj)) {
            $operatingEfficiency = $res[0]['operating_efficiency'];
        }
        $emission  = new ControlEmissionService();
        $emissions = $emission->getControlEmissionTotalByFacilityId($facility_id, $plan_number);//设施排放量总和
        $result    = $operatingEfficiency ? 1 - sprintf('%.3f', $emissions / $operatingEfficiency) : 1;
        return $result;
    }

    /**
     * 实时企业/模拟企业 - 减排前 - 单公司 - 脱硫脱硝 - 运行浓度
     * @param $plan_number
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getCompanyOperationConcentration($plan_number)
    {
        $em      = new EmissionService();
        $control = new ControlService();
        $endTime = $control->getBeforeEndTime($plan_number) . ' 00:00:00';
        $data    = [];
        //排放量
        $emission  = $em->getAllCompanyEmissionMinToHourAvg($endTime, 7, 'mg');
        $gasVolume = $this->getCompanyExportFlueGasVolumeAll($plan_number);

        foreach ($emission as $key => &$val) {
            foreach ($gasVolume as $k => &$value) {
                if ($val['company_id'] == $value['company_id']) {
                    $item = [];
                    $item['company_id']        = $val['company_id'];
                    $item['company_name']      = $val['company_name'];
                    $item['so2_concentration'] = !empty($value['so2_gas_volume']) && !empty($val['so2_emissions'])
                        ? sprintf('%.5f', $val['so2_emissions'] * 7 * 24 / $value['so2_gas_volume'])
                        : 0;
                    $item['no2_concentration'] = !empty($value['no2_gas_volume']) && !empty($val['nox_emissions'])
                        ? sprintf('%.5f', $val['nox_emissions'] * 7 * 24 / $value['no2_gas_volume'])
                        : 0;
                    array_push($data, $item);
                }
            }
        }
        return $data;
    }

    /**
     * 实时企业/模拟企业 - 减排前 - 单公司 - 脱硫脱硝  运行效率
     * @param string $plan_number
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/07/26
     */
    public function getCompanyOperatingEfficiency($plan_number)
    {
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';
        $true_ids  = Db::name('basic_company')
            ->where(['realtime_company' => 1,'delete_time' => 0])
            ->column('id');

        $match = [
            'publish_time'         => ['$gte' => $startTime, '$lt' => $endTime],
            'company_id'           => ['$in'  => $true_ids],
            'operating_efficiency' => ['$nin' => [1, NAN]]
        ];
        //实时企业  脱硫
        $sqlEmissionSO2 = [
            'aggregate' => 'company_industry_monitor_sulfur_minute',
            'pipeline'  => [
                [
                    '$project' => [
                        '_id'                  => 1,
                        'emissions'            => 1,
                        'operating_efficiency' => 1,
                        'company_id'           => 1,
                        'company_name'         => 1,
                        'publish_time'         => 1
                    ],
                ],
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => [
                            'company_id'   => '$company_id',
                            'company_name' => '$company_name',
                        ],
                        'so2_efficiency' => [
                            '$sum' => [ //求和
                                '$divide' => [ //相除
                                    '$emissions',
                                    ['$subtract' => [1, '$operating_efficiency']] //相减
                                ]
                            ]
                        ],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmissionSO2 = new \MongoDB\Driver\Command($sqlEmissionSO2);
        $sulfurDataObjSO2 = $this->mongodb->executeCommand('huanxin', $commandEmissionSO2);
        $resSO2 = mongoObjToArray($sulfurDataObjSO2);
        //实时企业  脱硝
        $sqlEmissionNO2 = [
            'aggregate' => 'company_industry_monitor_nitre_minute',
            'pipeline'  => [
                [
                    '$project' => [
                        '_id'                  => 1,
                        'emission'             => 1,
                        'facility_id'          => 1,
                        'operating_efficiency' => 1,
                        'company_id'           => 1,
                        'company_name'         => 1,
                        'publish_time'         => 1
                    ],
                ],
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => [
                            'company_id'   => '$company_id',
                            'company_name' => '$company_name',
                        ],
                        'no2_efficiency' => [
                            '$sum' => [ //求和
                                '$divide' => [ //相除
                                    '$emission',
                                    ['$subtract' => [1, '$operating_efficiency']] //相减
                                ]
                            ]
                        ],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmissionNO2 = new \MongoDB\Driver\Command($sqlEmissionNO2);
        $sulfurDataObjNO2   = $this->mongodb->executeCommand('huanxin', $commandEmissionNO2);
        $resNO2 = mongoObjToArray($sulfurDataObjNO2);
        $data   = [];
        foreach ($resSO2 as $val) {
            foreach ($resNO2 as $value) {
                if ($val['_id']->company_id == $value['_id']->company_id) {
                    $item = [];
                    $item['company_id']     = $val['_id']->company_id;
                    $item['company_name']   = $val['_id']->company_name;
                    $item['so2_efficiency'] = !is_nan($val['so2_efficiency']) && !empty($val['so2_efficiency'])
                        ? $val['so2_efficiency'] / (7 * 24)
                        : 0;
                    if ($val['_id']->company_id == $value['_id']->company_id) {
                        $item['no2_efficiency'] = !is_nan($value['no2_efficiency']) && !empty($value['no2_efficiency'])
                            ? $value['no2_efficiency'] / (7 * 24)
                            : 0;
                    }
                    array_push($data, $item);
                }
            }
        }
        //模拟企业 脱硫脱硝
        $monitor_ids = Db::name('basic_company')->where(['realtime_company' => 0])->column('id');
        $ids = implode(',', $monitor_ids);
        $sql = <<<SQL
            SELECT
                company_id,company_name,
                sum(convert(emissions_so2/(1 - operating_efficiency_so2),decimal(15,5)))/24 so2_efficiency,
                sum(convert(emissions_nox/(1 - operating_efficiency_nox),decimal(15,5)))/24 no2_efficiency
            FROM
                company_industry_monitor_simulation_hour_avg
            WHERE
                company_id IN ($ids)
            GROUP BY
                company_id
SQL;
        $monitorOperatingEfficiency = Db::query($sql);

        $data = array_merge($data, $monitorOperatingEfficiency);


        $em = new EmissionService();
        //排放量
        $emission = $em->getAllCompanyEmissionMinToHourAvg();

        $result = [];
        foreach ($emission as $val) {
            foreach ($data as $value) {
                if ($val['company_id'] == $value['company_id']) {
                    $item = [];
                    $item['company_id'] = $val['company_id'];
                    $item['company_name'] = $val['company_name'];
                    $item['so2_efficiency'] = !empty($value['so2_efficiency']) && !empty($val['so2_emissions'])
                        ? 1 - sprintf('%.5f', $val['so2_emissions'] * 7 * 24 / $value['so2_efficiency'])
                        : 1;
                    $item['no2_efficiency'] = !empty($value['no2_efficiency']) && !empty($val['nox_emissions'])
                        ? 1 - sprintf('%.5f', $val['nox_emissions'] * 7 * 24 / $value['no2_efficiency'])
                        : 1;
                    array_push($result, $item);
                }
            }
        }
        return $result;
    }

    /**
     * 实时企业 + 模拟企业 - 减排前  单行业  脱硫脱硝  运行浓度
     * @param int $industry_id 行业ID
     * @param string $plan_number 预案编号
     * @param string $type SO2  NO2
     * @return int|string
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy  2019/07/26
     */
    public function getIndustryOperationConcentration($industry_id, $plan_number, $type = 'SO2')
    {
        $em        = new ControlEmissionService();
        $emission  = $em->controlSingleIndustryTotalEmission($industry_id, $plan_number, $type);
        $gasVolume = $this->getIndustryExportFlueGasVolume($industry_id,$plan_number, $type);
        $operatingEfficiency = $gasVolume ? sprintf('%.3f', $emission / $gasVolume) : 0;
        return $operatingEfficiency;
    }

    /**
     * 实时企业 + 模拟企业 - 减排前 - 单行业 - 脱硫脱硝  运行效率
     * @param int $industry_id 行业ID
     * @param string $plan_number 预案编号
     * @param string $type SO2  NO2
     * @return int|string
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/07/26
     */
    public function getIndustryOperatingEfficiency($industry_id, $plan_number, $type = 'SO2')
    {
        $control   = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime   = $control->getBeforeEndTime($plan_number) . ' 00:00:00';

        if ($type == 'SO2') {
            $table = 'company_industry_monitor_sulfur_minute';
        } else {
            $table = 'company_industry_monitor_nitre_minute';
        }

        $companys = Db::name('basic_company')
            ->where([
                'industry_id'      => $industry_id,
                'realtime_company' => 1
            ])
            ->column('id');

        $match = [
            'publish_time'         => ['$gte' => $startTime, '$lt' => $endTime],
            'company_id'           => ['$in'  => $companys],
            'operating_efficiency' => ['$nin' => [1, NAN]]
        ];
        $sqlEmission = [
            'aggregate' => $table,
            'pipeline'  => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id'                  => null,
                        'operating_efficiency' => [
                            '$sum' => [ //求和
                                '$divide' => [ //相除
                                    '$emissions',
                                    ['$subtract' => [1, '$operating_efficiency']] //相减
                                ]
                            ]
                        ],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj = $this->mongodb->executeCommand('huanxin', $commandEmission);
        $res = mongoObjToArray($sulfurDataObj);
        $operatingEfficiency = 0;
        if ($res) {
            if (!is_nan($res[0]['operating_efficiency'])) {
                $operatingEfficiency = $res[0]['operating_efficiency'];
            }
        }

        //模拟企业
        if ($type == 'SO2') {
            $sql = <<<SQL
                SELECT
                    sum(convert(emissions_so2/(1 - operating_efficiency_so2),decimal(15,5))) operating_efficiency
                FROM
                    company_industry_monitor_simulation_hour_avg
                WHERE
                    industry_id = $industry_id
SQL;
        } else {
            $sql = <<<SQL
                SELECT
                    sum(convert(emissions_nox/(1 - operating_efficiency_nox),decimal(15,5))) operating_efficiency
                FROM
                    company_industry_monitor_simulation_hour_avg
                WHERE
                    industry_id = $industry_id
SQL;
        }
        $monitorOperatingEfficiency = Db::query($sql);
        if ($monitorOperatingEfficiency) {
            $operatingEfficiency += $monitorOperatingEfficiency[0]['operating_efficiency'] * 7;
        }
        $emission = (new ControlEmissionService())->controlSingleIndustryTotalEmission($industry_id, $plan_number, $type);
        $result = $operatingEfficiency ? 1 - sprintf('%.3f', $emission / $operatingEfficiency) : 1;
        return $result;
    }

    /**
     * 所有行业 - 减排前 - 脱硫脱硝 - 运行浓度
     * @param $plan_number
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/08/01
     */
    public function getIndustryOperationConcentrationAll($plan_number)
    {
        $operation_concentration_so2 = $this->getIndustryOperationConcentration(1, $plan_number, 'SO2');
        $operation_concentration_nox = $this->getIndustryOperationConcentration(1, $plan_number, 'NO2');

        $data = [
            [
                'industry_id' => 1,
                'operation_concentration_so2' => $operation_concentration_so2,
                'operation_concentration_nox' => $operation_concentration_nox
            ],
            [
                'industry_id' => 2,
                'operation_concentration_so2' => 30,
                'operation_concentration_nox' => 150
            ],
            [
                'industry_id' => 3,
                'operation_concentration_so2' => 180,
                'operation_concentration_nox' => 300
            ],
            [
                'industry_id' => 4,
                'operation_concentration_so2' => 200,
                'operation_concentration_nox' => 400
            ],
        ];
        return $data;
    }

    /**
     * 所有行业 - 减排前 - 脱硫脱硝 - 运行效率
     * @param $plan_number
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/08/01
     */
    public function getIndustryOperatingEfficiencyAll($plan_number)
    {
        $operating_efficiency_so2 = $this->getIndustryOperatingEfficiency(1, $plan_number, 'SO2');
        $operating_efficiency_nox = $this->getIndustryOperatingEfficiency(1, $plan_number, 'NO2');

        $data = [
            [
                'industry_id' => 1,
                'operating_efficiency_so2' => $operating_efficiency_so2,
                'operating_efficiency_nox' => $operating_efficiency_nox
            ],
            [
                'industry_id' => 2,
                'operating_efficiency_so2' => '0.8',
                'operating_efficiency_nox' => '0.8'
            ],
            [
                'industry_id' => 3,
                'operating_efficiency_so2' => '0.8',
                'operating_efficiency_nox' => '0.8'
            ],
            [
                'industry_id' => 4,
                'operating_efficiency_so2' => '0.8',
                'operating_efficiency_nox' => '0.8'
            ]
        ];
        return $data;
    }

    /**
     * 所有企业排口的运行浓度运行效率
     * @param $plan_number
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author yy by 2019/8/1
     */
    public function getAllCompanyDrainConcentrationEfficiency($plan_number)
    {
        $control = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number) . ' 00:00:00';
        $endTime = $control->getBeforeEndTime($plan_number) . ' 00:00:00';
        $true_ids = Db::name('basic_company')->where(['realtime_company' => 1, 'delete_time' => 0])->column('id');
        $match = [
            'publish_time' => ['$gte' => $startTime, '$lt' => $endTime],
            'company_id' => ['$in' => $true_ids],
            'operating_efficiency' => ['$nin' => [1, NAN]]
        ];
        //实时企业  脱硫
        $sqlEmissionSO2 = [
            'aggregate' => 'company_industry_monitor_sulfur_minute',
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => [
                            'company_id' => '$company_id',
                            'company_name' => '$company_name',
                            'drain_id' => '$drain_id',
                            'drain_name' => '$drain_name',
                        ],
                        'emissions_total' => ['$sum' => '$emissions'],
                        'gas_total' => ['$sum' => '$export_flue_gas_volume'],
                        'so2_efficiency' => [
                            '$sum' => [ //求和
                                '$divide' => [ //相除
                                    '$emissions',
                                    ['$subtract' => [1, '$operating_efficiency']] //相减
                                ]
                            ]
                        ],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmissionSO2 = new \MongoDB\Driver\Command($sqlEmissionSO2);
        $sulfurDataObjSO2 = $this->mongodb->executeCommand('huanxin', $commandEmissionSO2);
        $resSO2 = mongoObjToArray($sulfurDataObjSO2);
        //实时企业  脱硝
        $sqlEmissionNO2 = [
            'aggregate' => 'company_industry_monitor_nitre_minute',
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => [
                            'company_id' => '$company_id',
                            'company_name' => '$company_name',
                            'drain_id' => '$drain_id',
                            'drain_name' => '$drain_name',
                        ],
                        'emissions_total' => ['$sum' => '$emission'],
                        'gas_total' => ['$sum' => '$inlet_flue_gas_volume'],
                        'no2_efficiency' => [
                            '$sum' => [ //求和
                                '$divide' => [ //相除
                                    '$emission',
                                    ['$subtract' => [1, '$operating_efficiency']] //相减
                                ]
                            ]
                        ],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmissionNO2 = new \MongoDB\Driver\Command($sqlEmissionNO2);
        $sulfurDataObjNO2 = $this->mongodb->executeCommand('huanxin', $commandEmissionNO2);
        $resNO2 = mongoObjToArray($sulfurDataObjNO2);
        $real = [];
        foreach ($resSO2 as $val) {
            foreach ($resNO2 as $value) {
                if ($val['_id']->company_id == $value['_id']->company_id && $val['_id']->drain_id == $value['_id']->drain_id) {
                    $real[$val['_id']->company_id]['company_id'] = $val['_id']->company_id;
                    $real[$val['_id']->company_id]['drain_id'] = $val['_id']->drain_id;
                    $real[$val['_id']->company_id]['company_name'] = $val['_id']->company_name;
                    $real[$val['_id']->company_id]['drain_name'] = $val['_id']->drain_name;
                    $real[$val['_id']->company_id]['efficiency_so2'] = $val['so2_efficiency'] > 0 ? round(1 - $val['emissions_total'] / $val['so2_efficiency'], 3) : '';
                    $real[$val['_id']->company_id]['concentration_so2'] = $val['so2_efficiency'] > 0 ? round($val['emissions_total'] / $val['gas_total'], 1) : '';
                    $real[$val['_id']->company_id]['efficiency_nox'] = $value['no2_efficiency'] > 0 ? round(1 - $value['emissions_total'] / $value['no2_efficiency'], 3) : '';
                    $real[$val['_id']->company_id]['concentration_nox'] = $value['no2_efficiency'] > 0 ? round($value['emissions_total'] / $value['gas_total'], 1) : '';
                }
            }
        }
        //模拟企业 脱硫脱硝
        $monitor_ids = Db::name('basic_company')->where(['realtime_company' => 0, 'delete_time' => 0])->column('id');
        $ids = '(' . implode(',', $monitor_ids) . ')';
        $simulate = Db::query("select company_id,company_name,drain_id,drain_name, round(avg(operation_concentration_so2), 1) as concentration_so2, round(avg(operation_concentration_nox),1) as concentration_nox, round(avg(operating_efficiency_so2),1) as efficiency_so2, round(avg(operating_efficiency_nox),1) as efficiency_nox 
                                    from company_industry_monitor_simulation_hour_avg where company_id  in $ids group by company_id,drain_id");
        return array_merge($real, $simulate);
    }

    /**
     * 减排前七天运行浓度趋势图 - 单设施
     * @param $facilityId
     * @param $planNumber
     * @param $plan
     * @param string $type
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/08/02
     */
    public function getCompanyFacilityBeforeOperationConcentration($facilityId, $planNumber, $plan, $type = 'SO2')
    {
        $em = new ControlEmissionService();
        $emission = $em->getControlEmissionDayAverageByFacilityId($facilityId, $planNumber, true);//每天的排放量
        $emission = $this->my_sort($emission, 'publish_time');
        $gasVolume = $this->getCompanyFacilityExportFlueGasVolumeDay($planNumber,$facilityId, $type);
        $data = [
            'date' => [],
            'data' => []
        ];
        $item = [];
        for ($i = 0; $i < count($gasVolume); $i++) {
            $item[] = $plan;
        }
        array_push($data['data'], $item);
        $res = [];
        foreach ($emission as $val) {
            foreach ($gasVolume as $value) {
                if ($val['publish_time'] == $value['_id']->publish_time) {
                    $time = date('m/d', strtotime($val['publish_time']));
                    $volume = $value['export_flue_gas_volume'] ? sprintf('%.3f', $val['emissions'] / $value['export_flue_gas_volume']) : 0;
                    $data['date'][] = $time;
                    $res[] = $volume;
                }
            }
        }
        array_push($data['data'], $res);

        return $data;
    }

    /**
     * 减排前七天运行效率趋势图 - 单设施
     * @param $facilityId
     * @param $planNumber
     * @param $plan
     * @param string $type
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/08/02
     */
    public function getCompanyFacilityBeforeOperationEfficiency($facilityId, $planNumber, $plan, $type = 'SO2')
    {
        $em         = new ControlEmissionService();
        $emission   = $em->getControlEmissionDayAverageByFacilityId($facilityId, $planNumber, true);//每天的排放量
        $emission   = $this->my_sort($emission,'publish_time');
        $efficiency = $this->getCompanyFacilityOperationEfficiencyUnder($facilityId, $planNumber, $type);
        $data = [
            'date' => [],
            'data' => []
        ];
        $item = [];
        for ($i = 0; $i < count($efficiency); $i++) {
            $item[] = $plan;
        }
        array_push($data['data'], $item);
        $res = [];
        foreach ($emission as $val) {
            foreach ($efficiency as $value) {
                if ($val['publish_time'] == $value['_id']->publish_time) {
                    $time = date('m/d', strtotime($val['publish_time']));
                    $volume = $value['operating_efficiency']
                        ? 1 - sprintf('%.3f', $val['emissions'] / $value['operating_efficiency'])
                        : 1;
                    $data['date'][] = $time;
                    $res[] = $volume;
                }
            }
        }
        array_push($data['data'], $res);
        return $data;
    }

    /**
     * 减排前七天 - 运行效率公式的分母
     * @param $facility_id
     * @param string $plan_number
     * @param string $type
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author ayy 2019/08/02
     */
    public function getCompanyFacilityOperationEfficiencyUnder($facility_id, $plan_number, $type = 'SO2')
    {
        $control = new ControlService();
        $startTime = $control->getBeforeStartTime($plan_number);
        $endTime = $control->getBeforeEndTime($plan_number) . ' 00:00:00';
        if ($type == 'SO2') {
            $table = 'company_industry_monitor_sulfur_minute';
            $field = [
                'emissions',
                '$emissions',
            ];
        } else {
            $field = [
                'emission',
                '$emission'
            ];
            $table = 'company_industry_monitor_nitre_minute';
        }

        //实时企业
        $match               = [
            'publish_time'         => ['$gt' => date('Y-m-d 00:00:00',strtotime('-1 day',strtotime($startTime))), '$lte' => $endTime],
            'facility_id'          => (int)$facility_id,
            'operating_efficiency' => ['$nin' => [1, NAN]]
        ];
        $sqlEmission = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$project' => [
                        '_id' => 1,
                        $field[0] => 1,
                        'facility_id' => 1,
                        'operating_efficiency' => 1,
                        'publish_time' => ['$substr' => ['$publish_time', 0, 10]]
                    ],
                ],
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => [
                            'facility_id' => '$facility_id',
                            'publish_time' => '$publish_time',
                        ],
                        'operating_efficiency' => [
                            '$sum' => [ //求和
                                '$divide' => [ //相除
                                    $field[1],
                                    ['$subtract' => [1, '$operating_efficiency']] //相减
                                ]
                            ]
                        ],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj = $this->mongodb->executeCommand('huanxin', $commandEmission)->toArray();
        return mongoObjToArray($sulfurDataObj);
    }

    /**
     * 二位数组排序
     * @param $arrays
     * @param $sort_key
     * @param int $sort_order
     * @param int $sort_type
     * @return bool
     */
    function my_sort($arrays, $sort_key, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC)
    {
        if (is_array($arrays)) {
            foreach ($arrays as $array) {
                if (is_array($array)) {
                    $key_arrays[] = $array[$sort_key];
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
        array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
        return $arrays;
    }
}